package com.onenine.app.fragment;

import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.TransitionDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Looper;
import android.os.MessageQueue;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.design.widget.TabLayout;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.onenine.app.R;
import com.onenine.app.activity.PostPublishActivity;
import com.onenine.app.db.DataManager;
import com.onenine.app.model.CoterieItem;
import com.onenine.app.utils.CDataProcessor;
import com.onenine.app.utils.CHelper;
import com.onenine.app.utils.RoleResLoader;
import com.onenine.app.view.RoundFrameLayout;
import com.onenine.base.base.BaseFragment;
import com.onenine.base.utils.StatusBarUtils;
import com.onenine.common.util.ActivityUtils;
import com.onenine.common.util.SizeUtils;
import com.onenine.glide.GlideApp;

import java.util.List;

import static com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions.withCrossFade;

public class CommunityFragment extends BaseFragment implements View.OnClickListener, Runnable, RadioGroup.OnCheckedChangeListener {

    private CRecommendFragment mRecFragment;
    private CAttentionFragment mAttFragment;
    private RoundFrameLayout mRoundLayout;
    private RadioGroup mRadioGroup;
    private TabLayout mTabLayout;
    private View mBtnAdd;
    private ImageView mIvBackground;
    private int mTopRoundRadius;
    private Drawable mCurrentDrawable;

    @Override
    protected int getLayout() {
        return R.layout.fragment_community;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        StatusBarUtils.setTransparentForImageViewInFragment(getActivity(), null);
        super.onCreate(savedInstanceState);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void initView(View view) {
        mRoundLayout = view.findViewById(R.id.top_round_layout);
        mTabLayout = view.findViewById(R.id.tl_tab);
        mRadioGroup = view.findViewById(R.id.rg_tab);
        mBtnAdd = view.findViewById(R.id.btn_add);
        mIvBackground = view.findViewById(R.id.iv_background);
        mTopRoundRadius = SizeUtils.dp2px(24);
        mCurrentDrawable = ActivityCompat.getDrawable(getContext(), RoleResLoader
                .getRoleDrawableResourceId(RoleResLoader.DynamicResName.IC_COMMUNITY_TOP_ALL_BG));
        mIvBackground.setImageDrawable(mCurrentDrawable);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        if (hidden) {
            StatusBarUtils.setFullScreenLightMode(getActivity());
        } else {
            setDarkModeStyle();
            StatusBarUtils.setTransparentForImageViewInFragment(getActivity(), null);
        }
    }

    @Override
    protected void initListener() {
        mRadioGroup.setOnCheckedChangeListener(this);
        mBtnAdd.setOnClickListener(this);
    }

    /**
     * 设置状态栏白字样式
     */
    private void setDarkModeStyle() {
        Looper.myQueue().addIdleHandler(new MessageQueue.IdleHandler() {
            @Override
            public boolean queueIdle() {
                StatusBarUtils.setDarkMode(getActivity());
                return false;
            }
        });
    }

    @Override
    public void initData() {
        super.initData();
        mRadioGroup.check(R.id.rb_rec);
        List<CoterieItem> coterieList = DataManager.getAllCoteries();
        if (coterieList == null || coterieList.isEmpty()) {
            CDataProcessor.syncCoteries(this);
        } else {
            bindDataView(coterieList);
        }
    }

    /**
     * 改变顶部背景
     *
     * @param coterieItem
     */
    public void changeTopBarBackground(CoterieItem coterieItem) {
        if (coterieItem.getCoterieType() > 0) {
            GlideApp.with(this).load(coterieItem.getBackground())
                    .transition(withCrossFade())
                    .into(new SimpleTarget<Drawable>() {
                        @Override
                        public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                            startTransitionDrawableAnim(resource);
                        }
                    });
        } else {
            startTransitionDrawableAnim(ActivityCompat.getDrawable(getContext(), RoleResLoader
                    .getRoleDrawableResourceId(RoleResLoader.DynamicResName.IC_COMMUNITY_TOP_ALL_BG)));
        }
    }

    /**
     * 启动fade动画
     *
     * @param nextDrawable
     */
    private void startTransitionDrawableAnim(Drawable nextDrawable) {
        Drawable[] drawables = new Drawable[]{mCurrentDrawable, nextDrawable};
        TransitionDrawable transitionDrawable = new TransitionDrawable(drawables);
        transitionDrawable.startTransition(500);
        mIvBackground.setImageDrawable(transitionDrawable);
        mCurrentDrawable = nextDrawable;
    }

    /**
     * 显示圈子Tab列表
     *
     * @param coterieItemList
     */
    private void bindDataView(List<CoterieItem> coterieItemList) {
        CHelper.addAll2CoterieList(coterieItemList);
        mRecFragment.bindData(mTabLayout, coterieItemList);
    }

    /**
     * 设置选中fragment
     *
     * @param position
     */
    private void selectFragment(int position) {
        FragmentTransaction fragmentTransaction = getChildFragmentManager().beginTransaction();
        if (position == 0) {
            if (mRecFragment == null) {
                mRecFragment = new CRecommendFragment();
                fragmentTransaction.add(R.id.fl_container, mRecFragment);
            } else {
                fragmentTransaction.show(mRecFragment);
            }
            if (mAttFragment != null && !mAttFragment.isHidden()) {
                fragmentTransaction.hide(mAttFragment);
            }
        } else {
            if (mAttFragment == null) {
                mAttFragment = new CAttentionFragment();
                fragmentTransaction.add(R.id.fl_container, mAttFragment);
            } else {
                fragmentTransaction.show(mAttFragment);
            }
            if (mRecFragment != null && !mRecFragment.isHidden()) {
                fragmentTransaction.hide(mRecFragment);
            }
        }
        fragmentTransaction.commitAllowingStateLoss();
    }

    @Override
    public void run() {
        bindDataView(DataManager.getAllCoteries());
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btn_add) {
            ActivityUtils.startActivity(getActivity(), PostPublishActivity.class);
        }
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        setRadioGroupCheckState(group, checkedId);
        if (checkedId == R.id.rb_rec) {
            selectFragment(0);
            setRadioButtonStyle((TextView) group.getChildAt(0), true);
            setRadioButtonStyle((TextView) group.getChildAt(1), false);
            mTabLayout.setVisibility(View.VISIBLE);
            mRoundLayout.setDrawTopLeft(0);
            mRoundLayout.setDrawTopRight(0);
        } else {
            selectFragment(1);
            setRadioButtonStyle((TextView) group.getChildAt(0), false);
            setRadioButtonStyle((TextView) group.getChildAt(1), true);
            mTabLayout.setVisibility(View.GONE);
            mRoundLayout.setDrawTopLeft(mTopRoundRadius);
            mRoundLayout.setDrawTopRight(mTopRoundRadius);
        }
    }

    /**
     * 设置是否加粗样式
     *
     * @param textView
     * @param bold
     */
    private void setRadioButtonStyle(TextView textView, boolean bold) {
        textView.getPaint().setFakeBoldText(bold);
    }

    /**
     * 设置RadioGroup状态
     *
     * @param group
     * @param checkedId
     */
    private void setRadioGroupCheckState(RadioGroup group, int checkedId) {
        for (int i = 0; i < group.getChildCount(); i++) {
            RadioButton radio = (RadioButton) group.getChildAt(i);
            if (radio.getId() == checkedId) {
                radio.setTextSize(25);
                radio.setTextColor(Color.WHITE);
            } else {
                radio.setTextSize(15);
                radio.setTextColor(0x95ffffff);
            }
        }
    }

}
